 

package c.x.jy.api.utils;

import java.util.Date;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import c.x.jy.common.exception.RRException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * jwt工具类
 *
 
 */
@Slf4j
  @Data
@ConfigurationProperties(prefix = "smartlock.jwt")
@Component
public class JwtUtils {
 

    private String secret;
    private long expire;
    private String header;
    public static  JwtUtils jwtUtils;
    @PostConstruct
   public   void init() {
    	jwtUtils=this;
 
   }

    /**
     * 生成jwt token
     */
    public String generateToken(long userId) {
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId+"")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            log.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * token是否过期
     * @return  true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
    
	public Long getLoginUserId(String token) {
		String userId = null;
		if ((token != null) && (token.length() > 7)) {
			Claims claims = getClaimByToken(token);// JwtFactory.parseJWT(auth);
			if (claims != null&&!isTokenExpired(claims.getExpiration())) {
				userId = StringUtils.isEmpty(claims.getSubject())   ? null: claims.getSubject()  ;//claims.get("sub").toString();
			}else if(claims==null||isTokenExpired(claims.getExpiration())) {
			      throw new RRException("登陆信息已过期，请重新登录", HttpStatus.UNAUTHORIZED.value());
			}
		}
		return userId==null?null:Long.parseLong(userId);
	}
 
}
